package com.example.myapplication3.video;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.myapplication3.R;
import com.example.myapplication3.base.BaseActivity;
import com.example.myapplication3.video.adapter.VideoAdapter;
import com.example.myapplication3.video.bean.VideoItem;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class VideoActivity extends BaseActivity {
    private List<VideoItem> datalist;
    private VideoAdapter adapter;
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private int pageIndex;
    private int size = 24;
    private Uri selectedUri;

    @Override
    public int getLayoutMain() {
        return R.layout.activity_video;
    }

    @Override
    public void initData() {
        datalist = new ArrayList<>();

    }

    @Override
    public void initView() {
        setSupportActionBar(findViewById(R.id.toolbar));
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        refreshLayout=findViewById(R.id.smartrefreshlayout);
        adapter = new VideoAdapter(datalist, this);
        recyclerView = findViewById(R.id.recyclerview);
        setShowMode(VideoAdapter.MODE_LIST);
        refreshLayout.autoRefresh(200);
        recyclerView.setAdapter(adapter);
        registerForContextMenu(recyclerView);
    }

    @Override
    public void initListener() {
        refreshLayout.setOnRefreshListener( refreshLayout->{
            loadVideoData();
        });
        refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            loadVideoData();
        });

        adapter.setItemOnclickListener(new VideoAdapter.ItemOnclickListener() {
            @Override
            public void onClick(View view, int position) {
               VideoItem videoItem = datalist.get(position);
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setDataAndType(videoItem.getUri(), videoItem.getMimeType());
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 授予临时读取权限
                startActivity(intent);
            }
        });
        adapter.setItemOnLongclickListener(new VideoAdapter.ItemOnLongclickListener() {
            @Override
            public void onLongClick(View view, int position) {
               VideoItem videoItem =  datalist.get(position);
               selectedUri = videoItem.getUri();
            }
        });
    }

    private void loadVideoData() {
        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_MEDIA_VIDEO)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{
                            Manifest.permission.READ_MEDIA_VIDEO
                    },
                    1);
            return;
        } else {
            VideoQueryHelper.asynLoadAllVideos(this, pageIndex++, size, new VideoQueryHelper.VideoLoadCallback() {
                @Override
                public void onVideosLoaded(List<VideoItem> videos) {
                    if (videos==null){
                        Toast.makeText(VideoActivity.this,"没有数据",Toast.LENGTH_SHORT).show();
                        refreshLayout.finishRefresh(false);
                        refreshLayout.finishLoadMore(false);
                        return;
                    }
                    datalist.addAll(videos);
                    runOnUiThread(() -> {
                        adapter.notifyItemRangeChanged(pageIndex * size, size);
                        refreshLayout.finishRefresh(true);
                        refreshLayout.finishLoadMore(true);
                    });
                }
            });
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            loadVideoData(); // 权限通过后重试
        }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_imageview_show, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }if (item.getItemId() == R.id.menu_list) {
            setShowMode(VideoAdapter.MODE_LIST);
        }if (item.getItemId()==R.id.menu_grid){
            setShowMode(VideoAdapter.MODE_GRID);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getMenuInflater().inflate(R.menu.menu_longcilck,menu);
    }

    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
        if (item.getItemId()==R.id.menu_delete){
            // 假设你有要删除的照片的 Uri
            Uri uri = selectedUri; // 这里应该是你要删除的照片的 Uri

            try {
                // 删除媒体库中的记录
                int deletedRows = getContentResolver().delete(
                        uri,
                        null,
                        null
                );

                if (deletedRows > 0) {
                    // 删除成功
                    Toast.makeText(this, "照片已删除", Toast.LENGTH_SHORT).show();

                    // 可选：同时删除实际文件（某些设备可能需要）
                    String filePath = getPathFromUri(uri); // 需要实现这个方法
                    if (filePath != null) {
                        File file = new File(filePath);
                        if (file.delete()) {
                            Log.d("Delete", "文件已删除");
                        }
                    }
                } else {
                    Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
                }
            }
            catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "删除出错: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
        return super.onContextItemSelected(item);

    }
    public String getPathFromUri(Uri uri) {
        String path = null;
        String[] projection = {MediaStore.Video.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
            path = cursor.getString(columnIndex);
            cursor.close();
        }
        return path;
    }

    private void setShowMode(int mode) {
        adapter.setMode(mode);
        switch (mode) {
            case VideoAdapter.MODE_GRID:
                GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
                recyclerView.setLayoutManager(gridLayoutManager);
                break;
            case VideoAdapter.MODE_LIST:
            default:
                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
                recyclerView.setLayoutManager(linearLayoutManager);
                break;
        }
    }
}